﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BP.OA.Message;
namespace CCOA.App.Message
{
    public partial class SendMsg : System.Web.UI.Page
    {
        #region //1.公共接口(Public Interface)
        //权限控制
        private string FuncNo = null;
        private void Alert(string msg)
        {
            BP.OA.Debug.Alert(this, msg);
        }
        private string CurUserNo
        {
            get { return BP.Web.WebUser.No; }
        }
        private int rRe
        {
            get { return Convert.ToInt32(this.Request.QueryString["Re"]); }
        }
        private int rTrans
        {
            get { return Convert.ToInt32(this.Request.QueryString["Trans"]); }
        }
        //秦  根据操作类型
        private string OpeType
        {
            get { return this.Request.QueryString["OpeType"]; }
        }
        /// <summary>
        /// 获取路径函数
        /// </summary>
        /// <returns></returns>
        private string GetAttachPathName()
        {
            string dir = String.Format("/DataUser/UploadFile/Message/{0:yyyyMMdd}", DateTime.Now);
            return dir;
        }
        /// <summary>
        /// 获取新文件名函数
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private string GetAttachFileName(string fileName)
        {
            string f = System.IO.Path.GetFileNameWithoutExtension(fileName);
            string ext = System.IO.Path.GetExtension(fileName);
            string newFileName = String.Format("{0}_{1:yyyyMMddHHmmss}{2}", f, DateTime.Now, ext);
            return newFileName;
        }
        /// <summary>
        /// 加载默认接收人
        /// </summary>
        private void InitEmailReciver()
        {
            string msgType = this.Request.QueryString["MsgType"];
            if (string.IsNullOrEmpty(msgType))
                return;
            try
            {
                string receivers = "admin";
                switch (msgType)
                {
                    case "SystemMsg"://系统消息发送邮件
                        BP.Port.Emp emp = null;
                        if (string.IsNullOrEmpty(BP.Sys.SystemConfig.AppSettings["SystemMsgReceivers"]))
                        {
                            //默认发送给admin
                            emp = new BP.Port.Emp(receivers);
                            txt_Users.Text = emp.Name;
                            txt_UserNames.Value = emp.No;
                            return;
                        }
                        //从配置中取人员
                        receivers = BP.Sys.SystemConfig.AppSettings["SystemMsgReceivers"];
                        string[] usrs = receivers.Split(',');
                        string userNames = "";
                        foreach (string item in usrs)
                        {
                            emp = new BP.Port.Emp(item);

                            if (userNames.Length == 0)
                                userNames += emp.Name;
                            else
                                userNames += "," + emp.Name;
                        }
                        txt_Users.Text = userNames;
                        txt_UserNames.Value = receivers;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                this.Alert("邮箱默认加载人员出错：" + ex.Message);
            }
        }
        #endregion

        #region //2.页面装载(Page Load)
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (!BP.OA.GPM.IsCanUseFun(this.FuncNo)) { BP.OA.GPM.RedirectNoAccess(); return; }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InitEmailReciver();
                this.LoadData();
            }
        }
        private void LoadData()
        {
            if (this.rRe != 0)  //回复或转发时
            {
                string sSql = String.Format("select A.OID,Sender,A.AddTime,B.Title,B.Doc,B.AttachFile,B.SendToUsers from OA_MessageInBox A"
                                       + " inner join OA_Message B on A.FK_MsgNo=B.OID"
                                       + " where A.OID={0}", this.rRe);
                DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sSql);
                if (dt == null || dt.Rows.Count == 0) return;
                DataRow dr = dt.Rows[0];
                this.txt_Title.Text = String.Format("回复 {0}", dr["Title"]);

                this.txt_UserNames.Value = String.Format("{0}", dr["Sender"]);
                this.txt_Users.Text = BP.OA.GPM.GetUserNames(this.txt_UserNames.Value);
                string emailHeader = String.Format("<div style='background-color:#eeeeee;padding:2px 2px 2px 2px;'>发件人: {0}<br/>发送时间: {1:yyyy年MM月dd日 HH:mm:ss (ddd)}<br/>收件人:{2}<br/>主题:{3}</div>"
                              , BP.OA.GPM.GetUserNames(CurUserNo)
                              , Convert.ToDateTime(dr["AddTime"])
                              , this.txt_Users.Text
                              , dr["Title"]);
                this.txtContent.Text = String.Format("<br/><br/>------原始邮件------{1}<br/>{0}", dr["Doc"], emailHeader);
            }
            else if (this.rTrans != 0)
            {
                string sSql = String.Format("select A.OID,Sender,A.AddTime,B.Title,B.Doc,B.AttachFile,B.SendToUsers from OA_MessageInBox A"
                                       + " inner join OA_Message B on A.FK_MsgNo=B.OID"
                                       + " where A.OID={0}", this.rTrans);
                DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sSql);
                if (dt == null || dt.Rows.Count == 0) return;
                DataRow dr = dt.Rows[0];
                this.txt_Title.Text = String.Format("转发 {0}", dr["Title"]);

                this.txt_UserNames.Value = String.Format("{0}", dr["Sender"]);
                this.txt_Users.Text = BP.OA.GPM.GetUserNames(this.txt_UserNames.Value);
                string emailHeader = String.Format("<div style='background-color:#eeeeee;padding:2px 2px 2px 2px;'><b>发件人</b>: {0}<br/><b>发送时间</b>: {1:yyyy年MM月dd日 HH:mm:ss (ddd)}<br/><b>收件人</b>: {2}<br/><b>主题</b>: {3}</div>"
                              , BP.OA.GPM.GetUserNames(CurUserNo)
                              , Convert.ToDateTime(dr["AddTime"])
                              , this.txt_Users.Text
                              , dr["Title"]);
                this.txtContent.Text = String.Format("<br/><br/>------原始邮件------{1}<br/>{0}", dr["Doc"], emailHeader);
            }

        }
        private void ClearCtrl()
        {
            this.txt_UserNames.Value = String.Empty;
            this.txt_Users.Text = String.Empty;
            this.txtContent.Text = String.Empty;
        }

        #endregion

        #region //3.页面事件(Page Event)
        /// <summary>
        /// 发送 信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSendMsg_Click(object sender, EventArgs e)
        {
            // 1.获取UI值   
            string users = this.txt_UserNames.Value;
            string copyUsers = this.txt_CopyUserNames.Value;
            //如果抄送列表中存在
            string title = this.txt_Title.Text;
            string content = this.txtContent.Text;
            //string names = this.txt_Users.Text;
            string AttachFile = null;
            //附件

            // 2.验证   
            if (string.IsNullOrEmpty(users))
            {
                this.Alert("收件人不能为空"); return;
            }
            if (string.IsNullOrEmpty(title))
            {
                this.Alert("邮件标题不能为空"); return;
            }
            if (string.IsNullOrEmpty(content))
            {
                this.Alert("邮件内容不能为空"); return;
            }
            // 3.数据处理
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);
                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            BP.OA.Message.Message msg = new BP.OA.Message.Message();
            msg.AddTime = DateTime.Now;
            msg.Doc = content;
            msg.FK_UserNo = BP.Web.WebUser.No;
            msg.MessageState = 1;
            msg.SendToUsers = users;
            msg.CopyToUsers = copyUsers;
            msg.AttachFile = AttachFile;
            msg.Title = title;
            msg.Insert();
            msg.Doc = content;
            msg.Update();
            if (msg.OID == 0)
            {
                this.Alert("邮件发送失败！"); return;
            }
            if (true)
            {  //发件箱
                BP.OA.Message.SendBox sb = new BP.OA.Message.SendBox();
                sb.FK_MsgNo = msg.OID;
                sb.FK_SendUserNo = BP.Web.WebUser.No;
                sb.Receiver = users;
                sb.SendTime = DateTime.Now;
                sb.Insert();
            }
            if (true)
            {   //发送给收件人
                String[] arr_users = users.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String user in arr_users)
                {   //收件箱 n个人
                    BP.OA.Message.InBox ib = new BP.OA.Message.InBox();
                    ib.AddTime = DateTime.Now;
                    ib.FK_MsgNo = msg.OID;
                    ib.FK_ReceiveUserNo = user;
                    ib.Sender = BP.Web.WebUser.No;
                    ib.Received = false;
                    ib.IsCopy = false;  //是否抄送标志
                    ib.Insert();

                    int newId = ib.OID;
                    if (newId == 0) continue;
                    //发短消息
                    BP.OA.ShortMsg.Send_Email(user, title, "", newId.ToString(), false);
                }
            }
            if (true)
            {   //发送给抄送人
                String[] arr_users = copyUsers.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String user in arr_users)
                {   //收件箱 n个人
                    BP.OA.Message.InBox ib = new BP.OA.Message.InBox();
                    ib.AddTime = DateTime.Now;
                    ib.FK_MsgNo = msg.OID;
                    ib.FK_ReceiveUserNo = user;
                    ib.Sender = BP.Web.WebUser.No;
                    ib.Received = false;
                    ib.IsCopy = true;  //是否抄送标志
                    ib.Insert();

                    int newId = ib.OID;
                    if (newId == 0) continue;
                    //发短消息
                    BP.OA.ShortMsg.Send_Email(user, title, "", newId.ToString(), false);
                }
            }
            // 4.数据统计、日志
            // 5.提交或返回D:\ccflow\CCPortal\CCOA\CCOA\App\Message\SendBox.aspx
            this.Response.Redirect("~/App/Message/SendBox.aspx", true);
            //this.Alert(String.Format("消息发送成功！", names));
            //this.ClearCtrl();
        }
        protected void btnSaveMsg_Click(object sender, EventArgs e)
        {
            // 1.获取UI值   
            string users = this.txt_UserNames.Value;
            string copyUsers = this.txt_CopyUserNames.Value;
            string title = this.txt_Title.Text;
            string content = this.txtContent.Text;
            //string names = this.txt_Users.Text;
            string AttachFile = null;
            //附件

            // 2.验证   
            //if (string.IsNullOrEmpty(users))
            //{
            //    this.Alert("收件人不能为空"); return;
            //}
            //if (string.IsNullOrEmpty(content))
            //{
            //    this.Alert("邮件内容不能为空"); return;
            //}
            // 3.数据处理
            string dir = this.GetAttachPathName();
            if (!System.IO.Directory.Exists(Server.MapPath(dir)))
                System.IO.Directory.CreateDirectory(Server.MapPath(dir));
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    string newFileName = this.GetAttachFileName(hpf.FileName);
                    string path = String.Format("{0}/{1}", dir, newFileName);
                    //string filePath = this.FileUpload1.PostedFile.FileName;
                    try
                    {
                        hpf.SaveAs(Server.MapPath(path));
                        AttachFile += String.Format("{0};", path);
                    }
                    catch
                    {
                        ;
                    }
                }
            }
            BP.OA.Message.Message msg = new BP.OA.Message.Message();
            msg.AddTime = DateTime.Now;
            msg.Doc = content;
            msg.Title = title;
            msg.FK_UserNo = BP.Web.WebUser.No;
            msg.MessageState = 0;
            msg.SendToUsers = users;
            msg.CopyToUsers = copyUsers;
            msg.AttachFile = AttachFile;
            msg.Insert();
            msg.Doc = content;
            msg.Update();
            if (msg.OID == 0)
            {
                this.Alert("邮件保存到草稿箱失败！"); return;
            }
            if (string.IsNullOrEmpty(title))
            {
                this.Alert("邮件标题不能为空"); return;
            }
            if (true)
            {//草稿箱
                BP.OA.Message.DraftBox dft = new DraftBox();
                dft.AddTime = DateTime.Now;
                dft.FK_MsgNo = msg.OID;
                dft.FK_UserNo = BP.Web.WebUser.No;
                dft.Insert();
            }
            // 4.数据统计、日志
            // 5.提交或返回D:\ccflow\CCPortal\CCOA\CCOA\App\Message\DraftBox.aspx
            this.Response.Redirect("~/App/Message/DraftBox.aspx", true);
            //this.Alert(String.Format("邮件成功保存到草稿箱！"));
            //this.ClearCtrl();
        }
        #endregion
    }
}